package com.tony.study.thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: ThreadDemo02
 * @Auther: 皮蛋布丁
 * @Date: 2021/10/30/21:23
 * @Description: 实现多线程同步下载图片
 */
public class ThreadDemo02 extends Thread{

    private String url; //网络图片地址
    private String name;    //保存的文件名

    public ThreadDemo02(String url, String name) {
        this.url = url;
        this.name = name;
    }

    //下载图片的线程执行体
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为："+name);
    }

    public static void main(String[] args) {
        ThreadDemo02 t1 = new ThreadDemo02("https://avatar.csdnimg.cn/F/7/6/1_qq_42700766_1578631082.jpg","1.jpg");
        ThreadDemo02 t2 = new ThreadDemo02("https://avatar.csdnimg.cn/F/7/6/1_qq_42700766_1578631082.jpg","2.jpg");
        ThreadDemo02 t3 = new ThreadDemo02("https://avatar.csdnimg.cn/F/7/6/1_qq_42700766_1578631082.jpg","3.jpg");

        //先下载t1
        t1.start();
        //再下载t2
        t2.start();
        //最后下载t3
        t3.start();
    }
}

/**
* @Description: 下载器
* @Param:
* @return:
* @Author: 皮蛋布丁
* @Date: 2021/10/30 21:24
*/
class WebDownloader {
  //下载方法
  public void downloader(String url,String name) {
      try {
          FileUtils.copyURLToFile(new URL(url),new File(name));
      } catch (IOException e) {
          e.printStackTrace();
          System.out.println("IO异常，donloader方法出现问题");
      }
  }
}
